package net.doglog;

import java.io.*;

import javax.servlet.http.*;

@SuppressWarnings("serial")
public class FileServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String name = BlogUtil.parseName(req.getPathInfo());
		File file = FileUtil.getFile(name);
		
		if (file == null) {
			resp.setStatus(404);	// not found
		} else {
			/*
			 * 关于If-Modified-Since的处理：
			 * 	一个交流过程的Sample如下：
			 * 		imsString = Thu, 20 Aug 2009 13:47:04 GMT
			 * 		ims = 1250776024000
			 * 		lastModified = 1250776024340
			 * 	于是就能看到问题所在： ims是精确到秒的
			 * 	而我们保存的lastModified是精确到毫秒的
			 * 	所以应该比较秒数而不是直接比较long
			 */
			long ims = req.getDateHeader("If-Modified-Since");
			
			if (ims == -1 || ims / 1000 < file.getLastModified() / 1000) {	// changed
				resp.setCharacterEncoding("UTF-8");
				resp.setContentType(file.getContentType());
				resp.addDateHeader("Last-Modified", file.getLastModified());
				resp.addDateHeader("Expires", System.currentTimeMillis() + File.expire);
				resp.addHeader("Cache-Control", "public, max-age=" + File.maxAge);
				resp.getOutputStream().write(file.getContent());
			} else {
				resp.setStatus(304);	// not changed
			}
		}
	}
}
